//
//  SettingViewController.m
//  GPSRecord
//
//  Created by TianWan on 28/02/2017.
//  Copyright © 2017 天玩. All rights reserved.
//

#import "SettingViewController.h"
#import "Location.h"
#define iPhone4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)
#define iPad [[UIDevice currentDevice].model isEqualToString:@"iPad"]
@interface SettingViewController () <LocationDelegate, UITableViewDelegate, UITableViewDataSource>
{
    CGFloat _lastY;
    NSMutableArray *_timeArray;
}
@property (weak, nonatomic) IBOutlet UIView *bg;
@property (weak, nonatomic) IBOutlet UILabel *statusLabel;
@property (weak, nonatomic) IBOutlet UISwitch *statusSwitch;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _lastY = 0;
    _timeArray = [NSMutableArray array];
    [self adjustUI];
    [self addTips];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _timeArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    
    cell.textLabel.text = _timeArray[indexPath.row];
    
    return cell;
}


- (void)adjustUI
{
    self.bg.layer.cornerRadius = 5.0f;
    self.bg.clipsToBounds = YES;
}

- (void)addTips
{
    NSArray *tipStrs = @[@"由于应用涉及到位置信息收集及分析等服务，需要持续获取用户的定位信息，请安装后进行如下设置：",
                         @"1、打开桌面上的“设置”选项",
                         @"2、打开“隐私”选项页",
                         @"3、点击“定位服务”，将定位功能开启",
                         @"4、在隐私页面，选择“指挥一点通”，开启该应用的定位服务",
                         @"否则指挥一点通的管理端页面上将无法显示您的位置信息，不利于相关工作的展开～"];
    for (NSInteger i = 0; i < tipStrs.count ; i ++) {
        
        UIColor *textColor = (i == 0 || i == 5) ? [UIColor colorWithRed:50/255.0 green:50/255.0 blue:50/255.0 alpha:1] : [UIColor blackColor];
        UIFont *font;
        if (textColor == [UIColor blackColor]) {
            font = [UIFont boldSystemFontOfSize:16];
        }else {
            font = [UIFont systemFontOfSize:16];
        }
        
        NSString *str = tipStrs[i];
        UILabel *label = [[UILabel alloc] init];
        [self.bg addSubview:label];
        label.text = str;
        label.textColor = textColor;
        label.numberOfLines = 0;
        label.font = font;
        label.textAlignment = NSTextAlignmentLeft;
        NSDictionary *size16Dict = @{NSFontAttributeName: font};
        CGFloat labelW =  kUIScreenWidth - 16;
        CGFloat labelH = [str boundingRectWithSize:CGSizeMake(labelW, CGFLOAT_MAX) options:NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:size16Dict context:nil].size.height;
        if (_lastY == 0) {
            _lastY = 8;
        }
        label.frame = CGRectMake(8, _lastY, labelW, labelH);
        _lastY = _lastY + labelH + 8;
    }
}

- (IBAction)Switch:(UISwitch *)sender
{
    if (sender.on) {
        Location *l = [Location shareLocation];
        l.delegate = self;
        [l startLocation];
    }else {
        Location *l = [Location shareLocation];
        [l switchOff];
    }
}

- (void)Location:(Location *)location placemark:(CLPlacemark *)placemark
{
    NSLog(@"name:%@",placemark.name);
    NSLog(@"thoroughfare:%@",placemark.thoroughfare);
    NSLog(@"subThoroughfare:%@",placemark.subThoroughfare);
    NSLog(@"subLocality:%@",placemark.subLocality);
    NSLog(@"administrativeArea:%@",placemark.administrativeArea);
    NSLog(@"subAdministrativeArea:%@",placemark.subAdministrativeArea);
    NSLog(@"postalCode:%@",placemark.postalCode);
    NSLog(@"ISOcountryCode:%@",placemark.ISOcountryCode);
    NSLog(@"country:%@",placemark.country);
    NSLog(@"inlandWater:%@",placemark.inlandWater);
    NSLog(@"ocean:%@",placemark.ocean);
    //    NSLog(@"locality:%@",placemark.locality);
    
    
    NSString *address = [NSString stringWithFormat:@"%@%@(%@)",placemark.subLocality,placemark.name,placemark.thoroughfare];
}

- (void)Location:(Location *)location coordinate:(CLLocationCoordinate2D)coordinate
{
    NSString *longitude = [NSString stringWithFormat:@"%.10f",coordinate.longitude];
    NSString *latitude = [NSString stringWithFormat:@"%.10f",coordinate.latitude];
    [self uploadDataWithLongitude:longitude latitude:latitude];
    [self mapuploadDataWithLongitude:longitude latitude:latitude];
}

- (void)uploadDataWithLongitude:(NSString *)longitude latitude:(NSString *)latitude
{
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:kopenID];
    NSString *createtime = [self createtime];
    NSDictionary *param = @{
                            @"phone":openID,
                            @"longitude":longitude,
                            @"latitude":latitude,
                            @"createtime":createtime
                            };
    NSArray *array = @[param];
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *model;
    if (iPhone4) {
        model = @"iPhone4";
    }else if(iPhone5){
        model = @"iPhone5";
    }else if(iPhone6){
        model = @"iPhone6";
    }else if(iPhone6Plus){
        model = @"iPhone6Plus";
    }else {
        model = @"unknownDevice";
    }
    NSString *userAgent = [NSString stringWithFormat:@"ios%@/apple/%@",version,model];
    NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString *url = @"http://zhydt.lestar-edu.com/sendpoint";
    [[NetServer shareInstance] POST:url parameters:array userAgent:userAgent uuid:uuid resultBlock:^(id result) {
        if (result) {
            dispatch_async(dispatch_get_main_queue(), ^{
               [self addTimeStr];
            });
        }
    } errorBlock:^(id error) {
        if (error) {
            NSError *error = error;
            dispatch_async(dispatch_get_main_queue(), ^{
                [CustomToastView toast:error.localizedDescription];
            });
        }
    } withDialog:NO model:self];
}

- (void)addTimeStr
{
    NSString *timeStr = [self createtime];
    [_timeArray addObject:timeStr];
    [self.tableView reloadData];
}

// 图型显示
- (void)mapuploadDataWithLongitude:(NSString *)longitude latitude:(NSString *)latitude
{
    NSString *openID = [[NSUserDefaults standardUserDefaults] objectForKey:kopenID];
    NSString *avatar = [[NSUserDefaults standardUserDefaults] objectForKey:kavatar];
    NSString *nickname = [[NSUserDefaults standardUserDefaults] objectForKey:knickname];
    NSString *createtime = [self createtime];
    
    NSDictionary *param = @{
                            @"data":@[@{@"staus":@0,
                                      @"longitude":longitude,
                                      @"latitude":latitude,
                                      @"time":createtime
                                      }],
                            @"wechat" : @{
                                    @"acc":openID,
                                    @"avatar":avatar,
                                    @"nick":nickname
                                    }
                            };
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *model;
    if (iPhone4) {
        model = @"iPhone4";
    }else if(iPhone5){
        model = @"iPhone5";
    }else if(iPhone6){
        model = @"iPhone6";
    }else if(iPhone6Plus){
        model = @"iPhone6Plus";
    }else {
        model = @"unknownDevice";
    }
    NSString *userAgent = [NSString stringWithFormat:@"ios%@/apple/%@",version,model];
    NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    NSString *url = @"http://120.76.162.83:3000/api/v1/location";
    
    [[NetServer shareInstance] MapPOST:url parameters:param userAgent:userAgent uuid:uuid resultBlock:^(id result) {
        if (result) {
            
        }
    } errorBlock:^(id error) {
        if (error) {
            NSError *error = error;
            dispatch_async(dispatch_get_main_queue(), ^{
                [CustomToastView toast:error.localizedDescription];
            });
        }
    } withDialog:NO model:self];
}

- (NSString *)createtime
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate:date];
    return currentDateStr;
}

@end
